package com.lizemin.beanpostprocessor.extension;

import cn.hutool.json.JSONUtil;
import com.lizemin.beanpostprocessor.entity.Dog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author lzm
 * @date 2025/7/4 20:21
 * @description
 */
@Component
@Slf4j
public class BeanPostHandler implements BeanPostProcessor {

    /**
     * 在bean属性赋值后，初始化之前执行，也就是initializeBean的afterPropertiesSet之前执行或者@postConstruct注解方法执行之前执行
     *
     * @param bean     bean
     * @param beanName bean的名字
     * @return 处理后的bean
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        log.info("在初始化{}之前执行，也就是initializeBean的afterPropertiesSet之前执行", beanName);
        if ("dog".equals(beanName)) {
            log.info("开始修改bean的属性值，beanName = {}, bean = {}", beanName, JSONUtil.toJsonStr(bean));
            // 修改bean的属性
            Dog dog = (Dog) bean;
            dog.setAge(100);
            return dog;
        }
        return bean;
    }

    /**
     * 在bean完全初始化之后执行，也就是initializeBean的afterPropertiesSet之后执行或者@postConstruct注解方法执行之后执行
     *
     * @param bean     bean
     * @param beanName bean的名字
     * @return 处理后的bean
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        log.info("在初始化{}之后执行，也就是initializeBean的afterPropertiesSet之后执行", beanName);
        if ("beanService".equals(beanName)) {
            // 返回代理bean，从而实现动态代理
            return ProxyUtil.getProxy(bean);
        }
        return bean;
    }

}
